package cn.openread.demo.netty.danmu;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * Websocket 聊天服务器-服务端
 */
public class WebsocketDanmuServer {

    private int port;

    public WebsocketDanmuServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8080;
        }
        new WebsocketDanmuServer(port).run();

    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);
        try {
            ServerBootstrap b = new ServerBootstrap(); // (2)
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // (3)
                    .childHandler(new WebsocketDanmuServerInitializer())  //(4)
                    .option(ChannelOption.SO_BACKLOG, 128)          // (5)
                    .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

            System.out.println("SnakeGameServer 启动了" + port);

            // 绑定端口，开始接收进来的连接
            ChannelFuture f = b.bind(port).sync(); // (7)

            // 等待服务器  socket 关闭 。
            // 在这个例子中，这不会发生，但你可以优雅地关闭你的服务器。
            f.channel().closeFuture().sync();

        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();

            System.out.println("SnakeGameServer 关闭了");
        }
    }

    public static class WebsocketDanmuServerInitializer extends
            ChannelInitializer<SocketChannel> {    //1

        @Override
        public void initChannel(SocketChannel ch) throws Exception {//2
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("http-decodec", new HttpRequestDecoder());
            pipeline.addLast("http-aggregator", new HttpObjectAggregator(65536));
            pipeline.addLast("http-encodec", new HttpResponseEncoder());
            pipeline.addLast("http-chunked", new ChunkedWriteHandler());
       /*
			pipeline.addLast(new HttpServerCodec());
			pipeline.addLast(new HttpObjectAggregator(64*1024));
			pipeline.addLast(new ChunkedWriteHandler());
		*/
            pipeline.addLast("http-request", new HttpRequestHandler("/ws"));
            pipeline.addLast("WebSocket-protocol", new WebSocketServerProtocolHandler("/ws"));
            pipeline.addLast("WebSocket-request", new TextWebSocketFrameHandler());

        }
    }
}